Django框架(四):django的基本包及静态文件static的介绍 | 您所在的位置:网站首页 › 如何管理静态文件如图片、JavaScript、CSS Django 文档 › Django框架(四):django的基本包及静态文件static的介绍 |
目录 一、Request --> HttpResponse & render 1. httpresponse; 2.render; 二、静态文件static 三、在html文件中导入静态文件static里面的文件的两种方法(以导入js文件为例),推荐第二种; 1.第一种: 2.第二种:(推荐) 一、Request --> HttpResponse & render 1. httpresponse;在views.py文件下,导入HttpResponse第三方包,from django.shortcuts import HttpResponse; 服务器将相关数据信息封装为请求对象req,返回值给前端是HttpResponse字符串对象; 注意:一个请求对象request对应一个响应对象HttpResponse 2.render;在views.py文件下,导入render 第三方包, from django.shortcuts import render;上面说过:一个请求对象request对应一个响应对象HttpResponse;其实render包是 HttpResponse 包的渲染,其源代码如下: def render(request, template_name, context=None, content_type=None, status=None, using=None): """ Return a HttpResponse whose content is filled with the result of calling django.template.loader.render_to_string() with the passed arguments. """ content = loader.render_to_string(template_name, context, request, using=using) return HttpResponse(content, content_type, status)之后的render_to_response也是HttpResponse 包的渲染;所有的返回值都是HttpResponse字符串对象; 二、静态文件static在pycharm中创建一个工程project下第一层的文件夹static(即:与app应用一个层级的目录); 配置: 1.在工程project中的共用的settings中,首先确认INSTALLED_APPS中,包含:django.contrib.staticfiles 2.仍然在settings中,添加字段: STATICFILES_DIRS = [ os.path.join(BASE_DIR,"static"), ]主要作用是添加静态文件static的绝对路径,让django可以找到static文件夹; 3.说明:在settings文件中,包含:STATIC_URL = '/static/' ;这句话主要作用是起到静态文件static别名的作用,在任何位置导入静态文件夹里面的文件,都用别名:"/static/xxxxx文件"(即:/static/开头) 三、在html文件中导入静态文件static里面的文件的两种方法(以导入js文件为例),推荐第二种; 1.第一种: 2.第二种:(推荐){% load staticsfiles %} 说明:不管你用哪一种方式导入静态文件,在浏览器中,都会显示成 上面脚本中的{%%}都是渲染,最终在浏览器中都是一样的; |
CopyRight 2018-2019 实验室设备网 版权所有 |